<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#example').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>

<?php
@set_time_limit(0);

$fr_hr_selected = 'selected';
$fr_min_selected = 'selected';
$to_hr_selected = 'selected';
$to_min_selected = 'selected';

if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
  $fr_hr_selected = '';
  $fr_min_selected = '';
  $to_hr_selected = '';
  $to_min_selected = '';
  
}
function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}
function getClosestElement($array, $value) 
{
	$size = count($array);
	$tmp = -1;
	if ($size > 0) 
	{
		//echo max($array)."<br><br>";
		//$ret = max($array);
		 while (list($key, $va) = each($array)) 
		 {			 
			 $diff = abs($va - $value);			
			 if($tmp == -1)
			 {
				 $tmp = $diff;
				 $k = $key;
				 //echo "1st ".$key." & ".$diff." = ".$value." diff ".$tmp."<br><br><br>";
				
			 }
			 else
			 {
				 //echo $key." & ".$diff." = ".$value." diff ".$tmp."<br>";
				 if($tmp > $diff) 
				 {
					 $tmp = $diff;
					 $k = $key;
				 }
			}
		}
		//echo "<br> ".$key." ".$va." & ".$diff." = ".$value." diff ".$tmp."<br>";
		return $k;
		//echo "<br><br>";
	}
	else 
	{
	  return NULL;
	}
	
}
if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	

?>
<script type="text/javascript" language="javascript">

function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{
		//document.getElementById('popup_div').style.display = '';
		//document.getElementById('popup_div').style.visibility = 'visible';
		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}
function sendCSVData()
{
//alert(c1);
document.frmCSVData.submit();
//	window.location.href='export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5;
	//document.write('export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5);
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}

function getAddress(lat,long,div)
{
	var addr="";
	address=(lat+","+long);
	var geocoder2 = new GClientGeocoder();
geocoder2.getLocations(address, function(response) {
  if (!response || response.Status.code != 200) {
	//alert("Status Code:" + response.Status.code);
	//document.getElementById(div).innerHTML= "Status Code:"+response.Status.code;
	if(response.Status.code==620)
	  {
		 getAddress(lat,long,div);
	  }
  } else {
	place = response.Placemark[0];
	addr=place.address;
	addr=addr.split(",");
	//alert(place.address);
	document.getElementById(div).innerHTML=addr[0]+","+addr[1]+","+place.AddressDetails.Country.CountryNameCode;
}
});
}
function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';
	//document.getElementById('popup_div').style.visibility = 'hidden';	
	//document.getElementById('popup_div').style.display = 'none';
}



function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    //var difference_ms = Math.abs(date1_ms - date2_ms)
	var difference_ms = date1_ms - date2_ms
	    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}



function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  {
   alert("Select Device"); 
   document.getElementById('map_device_id').focus();
   return 0;  
  }
  
  if(document.getElementById('from_date').value=='')
  {
   alert("Select Date");
   document.getElementById('from_date').focus();
   return 0;  
  }
  return 1;
}
$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>

<div id="">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final">
<tr><th colspan="5">Master Report</th></tr>
  <tr>
    <td width="15%" align="right"><span class="form_text">Select Device</span></td>
    <td width="25%" align="left">
        <select name="map_device_id" id="map_device_id" tabindex="1" style="width:50%" onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text">
        <option value="0">Select Device</option>
        <?php 
		while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
		{
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } } ?>	
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td width="15%" align="right"><span class="form_text">Select Date</span></td>
    <td width="25%" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="2" size="12" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/>&nbsp;
    </td>
    <td style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=mapReport';" tabindex="7" /> 
</td>
  </tr>
</table>
</form>
</div>

<div id="popup_div" style=" display:block; border:0px;" >

</div>

<?php
//print_r($_POST);
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
	$srcData = explode("#",$_POST[map_device_id]);
	$devModel = "";
	
?>

<?php	
	$getDeviceModel = "SELECT * FROM tb_deviceinfo WHERE di_imeiId = '".$srcData[1]."' AND di_clientId = ".$_SESSION[clientID]." AND di_status = 1";
	$resDeviceModel = mysql_query($getDeviceModel);
	if(@mysql_affected_rows() > 0)
	{
		$fetDeviceModel = @mysql_fetch_assoc($resDeviceModel);
		//print_r($fetDeviceModel);
		if($fetDeviceModel[di_inputPort]!='')
		{
			$tabHead = "";
			$paramPort = "";
			$portDetails1 = explode("#",$fetDeviceModel[di_inputPort]);
			for($k=1;$k<count($portDetails1);$k++)
			{						
				if($portDetails1[$k-1]!="")
				{
					$portDetails2 = explode("_",$portDetails1[$k-1]);
					$tabHead .= "<th width='5%'>".$portDetails2[0]."</th>";
					$paramPort .= $portDetails2[1]."#";
				}
			}
		}
		/*if($fetDeviceModel[di_outputPort]!='')
		{
			$portDetails1 = explode("#",$fetDeviceModel[di_outputPort]);
			for($k=1;$k<count($portDetails1);$k++)
			{						
				if($portDetails1[$k-1]!="")
				{
					$portDetails2 = explode("_",$portDetails1[$k-1]);
					echo $portDetails2[0];
				}
			}
		}
		*/
	}
	//echo $devModel;
	//exit;
?>
<div class="info_port">Master Report - <?php echo $srcData[0];?></div>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">      
  <thead>
    <tr>
     <th width="1%">#</th>
     <th width="5%">Date</th>
     <th width="7%">Time</th>
     <th width="10%">Latitude & Longitude</th>
     <th width="4%">Speed</th>
     <th width="4%">Distance</th>
     <th width="4%">Altitude</th>     
     <th width="4%">Direction</th>
     <?php if($fetDeviceModel[di_inputPort]!='') { echo $tabHead; } ?>
    </tr>
 </thead>
 <tbody>
    
<?php
$fuel_sql ="select * from tb_deviceinfo,tb_fuel where imei = di_imeiId AND di_imeiId = '".$srcData[1]."' order by voltage ASC";
$fuel_rows = $db->query($fuel_sql);
$k=0;
while($fuel_result = @mysql_fetch_assoc($fuel_rows))
{
	$fuel_params[$fuel_result[tanksize]] = $fuel_result[voltage];
	$fuel_port = $fuel_result[di_Fuelport];
	$k++;
}

//$edate = $_POST[to_date];

//$z = GetDays($sdate, $edate);
$cnt = 1;
$tmp=-1;
$t1=0.0;
$t2=0.0;
$timeArr= array();
$totalDistance=0;

	$file = DATAPATH.date("d-m-Y", strtotime($_POST[from_date]))."/".$srcData[1].".txt";   
	if(chk_folder($file))
	{
		$file1 = @fopen($file, "r");
		if($file1)
		{
			while(!feof($file1))
			{
				$data= @fgets($file1);
			}
		}
		@fclose($file1);
		
		 $data = getSortedData($data);
		 $data1=explode("#",$data);
		 for($j1=0;$j1<count($data1);$j1++)
		 {
			$data2=explode("@",$data1[$j1]);
			if(count($data2)>1)
			{
			$data3=explode(",",$data2[1]);
			
			$geodate = date("d-m-Y",strtotime($data3[8]));
			$geoTime = $data3[9];
			$curTime = explode(":",$data3[9]);
			$curTime = (($curTime[0] * 60) + $curTime[1]);
			//echo $show;
			$vehi=$data3[0];
			$pos1=calLat($data3[2]);
			$pos2=calLong($data3[1]);
			
			if($pos1>0 && $pos2>0)
			{
				if(!in_array($geoTime,$timeArr) )
				{
				//echo round($data3[9]);
					if($cnt==1)
					{
						$pits1 =  $pos1;
						$pits2 =  $pos2;
					}
					else
					{
						$pits3 =  $pos1;
						$pits4 =  $pos2;
						
						$dist = getDistance($pits1, $pits2, $pits3, $pits4);
						$totalDistance += $dist;
						$pits1 =  $pits3;
						$pits2 =  $pits4;
					}
					$pport = explode("#",$paramPort);
					$protVal = "";
					for($r = 0;$r < count($pport)-1; $r++)
					{
						if(splitParameter($pport[$r],$data3[7]) == 1)						
							$protVal .= "<td>On</td>";
						else
							$protVal .= "<td>Off</td>";
					}
					
					
					//exit;
					$fule_param = $data3[7]; 
					$d = preg_split("/[\s,]+/",$fule_param);
					foreach($d as $e)
					{
						// fuel port
						if(substr($e,0,3)=='['.$fuelPort.'=')
						{
							$v = str_replace(array('['.$fuelPort.'=',']'),'',$e); 
							if(strlen($v) >= 3 )
							{
								$v = $v/1000;
								$fuelData = getClosestElement($fuel_params,$v)." ltrs";
							}
							else 
							{
								$fuelData = $v." mv";
							}

						}
						// AC port
						if(substr($e,0,3)=='['.$acPort.'=')
						{
							  $acData = (str_replace(array('['.$acPort.'=',']'),'',$e)) ? "On" : "Off"; 
						}
						//Ignition port
						if(substr($e,0,3)=='['.$ignitPort.'=')
						{
							  $ignitData = str_replace(array('['.$ignitPort.'=',']'),'',$e) ? "On" : "Off";  
						}
						//Engine Port
						if(substr($e,0,3)=='['.$engPort.'=')
						{
							  $engineData = str_replace(array('['.$engPort.'=',']'),'',$e) ? "On" : "Off";  
						}
						
						//SOS port
						if(substr($e,0,3)=='['.$sosPort.'=')
						{
							  $sosData = str_replace(array('['.$sosPort.'=',']'),'',$e) ? "On" : "Off";  
						}
						
					 }
					
			//if($tmp != round($totalDistance))
			//{
			
			//$res=simpleGeocode($pos1,$pos2);
			//print_r($res);
			//$res=str_replace('"',"",$res);
?>	  
      <tr <?php if($cnt % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
		<td><?php echo $cnt; ?></td>
		<td><?php echo $geodate; ?></td>
        <td><?php echo date('h:i:s A',strtotime($geoTime)); ?></td>
		<td><?php echo '<a href=http://maps.google.com/maps?q='.$pos1.','.$pos2.' target=_blank title=click here>'.$pos1.'&'.$pos2.'</a>';	?></td>
		<td><?php echo $data3[3]; ?></td>
   		<td><?php echo round($totalDistance); ?></td>
        <td><?php echo $data3[5]; ?></td>
        <td><?php echo $data3[4]; ?></td>
        <?php if($fetDeviceModel[di_inputPort]!='') { echo $protVal; } ?>
    </tr>
 <?php   
				$cnt++; 
				//$tmp=round($totalDistance);
			//}
				array_push($timeArr,$geoTime);
			}
			}
		}
	}
		
	}
?>	  
 </tbody>
</table>
<?php
  
}///end of post

?>
